<template>
	<div>
		<el-dialog v-model="dialogVisible" :title="id ? '编辑科目' : '新增科目'">
			<el-form inline>
				<el-form-item label="科目名称">
					<el-input v-model="form.subjectName"></el-input>
				</el-form-item>
				<el-form-item label="状态">
					<el-radio-group v-model="form.enabled">
						<el-radio v-for="item in dicts.system_global_status" :key="item.k" :label="Number(item.v)">
							{{ item.k }}
						</el-radio>
					</el-radio-group>
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button @click="dialogVisible = false">取消</el-button>
				<el-button type="primary" @click="onSubmit">确认</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts">
import { getSubjectGetApi, postSubjectAOUApi } from '@renderer/api/subject';
import { useDicts } from '@renderer/composables/dicts';
import { SubjectForm } from '@renderer/interface/subject';
import { ref, watch } from 'vue';

// 父组件传参
const props = defineProps<{
	id: string
}>()
// 自定义事件
const emits = defineEmits(['addSuccess'])
// 接收父组件的 v-model
const dialogVisible = defineModel({ default: false })

/* 表单数据 */
const formValue = () => ({
	subjectName: '',
	enabled: -1,
})
const form = ref<SubjectForm>(formValue())
const { dicts } = useDicts(['system_global_status'])

// 根据id获取详情数据
const getFormData = async () => {
	const { code, data } = await getSubjectGetApi(props.id)
	if (code !== '200') return

	form.value = data
}

/* 确认按钮 */
// 提交数据
const postRoleData = async () => {
	const { code } = await postSubjectAOUApi(form.value)
	if (code !== '200') return

	ElMessage({
		type: 'success',
		message: form.value.id ? '修改科目成功~' : '添加科目成功~'
	})
	dialogVisible.value = false

	// 通知父组件
	emits('addSuccess')
}
// 点击确认按钮
const onSubmit = () => {
	postRoleData()
}

watch(dialogVisible, () => {
	if (dialogVisible.value) {
		// 打开 dialog 时获取数据
		props.id && getFormData()
	} else {
		// 关闭 dialog 时清空数据
		form.value = formValue()
	}
})
</script>

<style scoped lang="scss"></style>